package com.micro.fast.upms.controller;

import com.micro.fast.common.exception.UserException;
import com.micro.fast.common.response.ServerResponse;
import com.micro.fast.upms.pojo.UpmsUser;
import com.micro.fast.upms.service.UpmsUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * 权限管理系统用户管理
 *
 * @author lsy
 */
@RestController
@RequestMapping(value = "/upms/user")
public class UpmsUserController {

  /**
   * 用户服务接口
   */
  @Autowired
  private UpmsUserService upmsUserService;

  /**
   * 用户注册,使用Valid注解对upmsUser进行参数校验
   * BindingResult一定要紧跟校验的对象
   * @return
   */
  @PostMapping
  public ServerResponse<UpmsUser> register(@Valid UpmsUser upmsUser,BindingResult errors
      , @RequestParam(defaultValue = "") String repeatPassword) {
    //对参数的校验抛出异常
    if (errors.hasErrors()) {
      errors.getAllErrors().stream().forEach(objectError -> {
        FieldError fieldError = (FieldError) objectError;
        throw new UserException(fieldError.getDefaultMessage());
      });
    }
    ServerResponse<UpmsUser> register = upmsUserService.register(upmsUser, repeatPassword);
    return register;
  }
}
